import React from 'react'
import {connect} from 'react-redux'
import { Form, message, InputNumber, Button, Spin, Divider } from 'antd';
import {messages} from "share/common";
import Calculator from "containers/financial-account/template/calculator";
import credentialService from "containers/financial-account/credential-definition/credential-definition-service";
import config from "config";
const FormItem = Form.Item;
import Chooser from "components/chooser";
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class rowRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      record: {},
      saveLoading: false,
      infoData: {},
      sceneDefineId: '',
      treeList: [],
      loading: false
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.setState({record: {}, infoData: {}, treeList: []});
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      record: nextProps.editRecord,
      infoData: nextProps.infoData,
      saveLoading: false,
      sceneDefineId: nextProps.editRecord ? nextProps.editRecord.sceneDefineId : ''
    },() => {
      const { infoData, sceneDefineId } = this.state;
      if(sceneDefineId){
        this.setState({loading: true});
        credentialService.getTreeList({functionDefineId: infoData.functionDefineId, sceneDefineId}).then(res => {
          this.setState({
            treeList: res.data,
            loading: false
          });
        }).catch(e => {
          this.setState({loading: false});
          message.error(e.response.data.message);
        })
      }
    });
  }

  handleSave = () => {
    const { record } = this.state;
    let temp = ['sceneDefineId', 'sequence'];
    record.journalLineTemplateDetails && record.journalLineTemplateDetails.map(item => {
      item.isCouldEdit && temp.push(item.lineDefineId);
    });
    this.props.form.validateFields(temp, (err,values) => {
      if(!err){
        const { infoData, sceneDefineId, record } = this.state;
        const { user } = this.props;
        let temp = {
          journalTemplateId: infoData.id,
          sequence: values.sequence,
          sceneDefineId
        };
        record.id && (temp.id = record.id);
        this.setState({saveLoading: true});
        let url = temp.id ? 'updateRowStyle' : 'saveRowStyle';
        credentialService[url](temp,user.userOID).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(e.response.data.message);
        })
      }
    })
  };

  render(){
    const { record, saveLoading, infoData, treeList, loading } = this.state;
    const { credentialDefinition } = this.props;
    const { getFieldDecorator } = this.props.form;
    return(
      <div>
        <Spin spinning={loading}>
        <Form style={{marginTop:'10px'}}>
          <FormItem label={messages('financial-account.key137')/*核算场景*/} {...formItemLayout}>
            {getFieldDecorator('sceneDefineId', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
              initialValue: record.sceneName ? [{id: record.sceneDefineId, sceneName: record.sceneName}] : []
            })(
              <Chooser
                selectorItem={{
                  title: messages('financial-account.key138')/*选择核算场景*/,
                  url: `${config.baseUrl}/ledger/api/scene/define/query/by/functionDefineId`,
                  searchForm: [{
                    type: 'input',
                    id: 'sceneCodeOrName',
                    label: messages('financial-account.key42')/*场景编码/名称*/
                  }],
                  columns: [
                    { title: messages('financial-account.key43')/*场景编码*/, dataIndex: 'sceneCode' },
                    { title: messages('financial-account.key44')/*场景名称*/, dataIndex: 'sceneName' }
                  ],
                  key: 'id',
                  listKey: "rows"
                }}
                valueKey="id"
                onChange={value => {
                  value[0] && this.setState({ sceneDefineId: value[0].id });
                }}
                listExtraParams={{ functionDefineId: infoData.functionDefineId }}
                labelKey="sceneName"
                single
                disabled={!!record.sceneName}
              />
            )}
          </FormItem>
          <FormItem label={messages('common.sequence')/*序号*/} {...formItemLayout}>
            {getFieldDecorator('sequence', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.sequence
            })(
              <InputNumber formatter={this.showPriority}
                           placeholder={messages('common.please.input')/*请输入*/}
                           parser={value => value}
                           min={1}/>
            )}
          </FormItem>
          <Divider/>
          {
            Object.keys(record).length > 0 &&
            record.journalLineTemplateDetails.map((item) => {
              return (
                <FormItem label={item.ledgerName} {...formItemLayout}>
                  {getFieldDecorator(item.lineDefineId, {
                    rules: [{
                      required: item.isNotEmpty, message: messages('common.please.enter')/*请输入*/,
                    }],
                    initialValue: item.cellComment
                  })(
                    <Calculator treeList={treeList}
                                disabled={!item.isCouldEdit}
                                infoData={{
                                  lineDefineId: item.lineDefineId,
                                  templateId: infoData.id,
                                  journalTemplateSceneId: record.id,
                                  isDcDirection: item.isDcDirection,
                                  setOfBooksId: credentialDefinition.setOfBooksId
                                }}/>
                  )}
                </FormItem>
              )
            })
          }
        </Form>
        </Spin>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={() => this.props.close(true)}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    user: state.login.user,
    tenant: state.login.tenant,
    credentialDefinition: state.financialAccount.credentialDefinition
  }
}

const wrappedRowRule = Form.create()(rowRule);
export default connect(mapStateToProps)(wrappedRowRule);
